//
//  SharedDBManager.m
//  RealMate_v_2
//
//  Created by DONG HWAN BAE on 10. 11. 7..
//  Copyright 2010 Ajou University. All rights reserved.
//

#import "SharedDBManager.h"
#import "Teximeter_coreAppDelegate.h"
#import "track.h"
#import "OptionValueManager.h"

static SharedDBManager* sharedInst = nil;

@implementation SharedDBManager



@synthesize fetchedResultsController=fetchedResultsController_, managedObjectContext=managedObjectContext_;

- (void)dealloc {
	[sharedInst release];
    [super dealloc];
}

//싱글톤으로 하기 위해서 하는 작업 초기화
+ (id)sharedInstance
{
	@synchronized( self ) {
		if ( sharedInst == nil ) {
			/* sharedInst set up in init */
			[[self alloc] init];
		}
	}
	return sharedInst;
}
//초기화 하기
- (id)init
{
	NSLog(@"init SharedDBManamger");
    if ( sharedInst != nil ) {
        [NSException raise:NSInternalInconsistencyException
					format:@"[%@ %@] cannot be called; use +[%@ %@] instead",
		 NSStringFromClass([self class]), NSStringFromSelector(_cmd), 
		 NSStringFromClass([self class]),
		 NSStringFromSelector(@selector(sharedInstance))];
	} else if ( self = [super init] ) {
		sharedInst = self;
		// 초기화할게 없당.. 패스
		if(self.managedObjectContext==nil)
		{
			Teximeter_coreAppDelegate* appDelegate = [[UIApplication sharedApplication]delegate];
			self.managedObjectContext = appDelegate.managedObjectContext;
		}
	}
	return sharedInst;
}
//리테인 카운트
- (NSUInteger)retainCount
{
	return NSUIntegerMax;
}

- (oneway void)release
{
}
//리테인
- (id)retain
{
	return sharedInst;
}
//오토릴리즈
- (id)autorelease
{
	return sharedInst;
}



-(void)deleteAllAddress
{
	NSFetchRequest * allCars = [[NSFetchRequest alloc] init];
	[allCars setEntity:[NSEntityDescription entityForName:@"track" inManagedObjectContext:self.managedObjectContext]];
	[allCars setIncludesPropertyValues:NO]; //only fetch the managedObjectID
	
	NSError * error = nil;
	NSArray * cars = [self.managedObjectContext executeFetchRequest:allCars error:&error];
	[allCars release];
	//error handling goes here
	for (NSManagedObject * car in cars) {
		[self.managedObjectContext deleteObject:car];
	}
	
}

-(void)deleteWithPredicate:(NSPredicate*)predicate
{
	NSFetchRequest * allCars = [[NSFetchRequest alloc] init];
	[allCars setEntity:[NSEntityDescription entityForName:@"track" inManagedObjectContext:self.managedObjectContext]];
	[allCars setIncludesPropertyValues:NO]; //only fetch the managedObjectID
	[allCars setPredicate:predicate];
	NSError * error = nil;
	NSArray * cars = [self.managedObjectContext executeFetchRequest:allCars error:&error];
	[allCars release];
	//error handling goes here
	for (NSManagedObject * car in cars) {
		[self.managedObjectContext deleteObject:car];
	}
}


-(NSArray*)selecAll
{
	NSFetchRequest * allCars = [[NSFetchRequest alloc] init];
	[allCars setEntity:[NSEntityDescription entityForName:@"track" inManagedObjectContext:self.managedObjectContext]];
	[allCars setIncludesPropertyValues:NO]; //only fetch the managedObjectID
	
	NSError * error = nil;
	NSArray * cars = [self.managedObjectContext executeFetchRequest:allCars error:&error];
	[allCars release];
	//error handling goes here
	return [[cars autorelease]retain];
}


-(NSArray*)selectWithPredicate:(NSPredicate*)predicate
{
	
	NSFetchRequest* request = [[[NSFetchRequest alloc]init]autorelease];
	NSEntityDescription* bundleDescription = [NSEntityDescription entityForName:@"track" inManagedObjectContext:self.managedObjectContext];
	[request setEntity:bundleDescription];
	

	NSSortDescriptor* sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"index" ascending:NO];
	NSArray* sortArray = [NSArray arrayWithObject:sortDescriptor];
	[request setSortDescriptors:sortArray];
	[request setFetchLimit:30];
	[request setPredicate:predicate];

	
	NSError* error;
	NSArray* array = [[[self.managedObjectContext executeFetchRequest:request error:&error]mutableCopy]autorelease];
	NSLog(@"REQUEST COUNT =%d",[array count]);
	if(array!=nil)
	{
		
		/*
		 for(int i=0;i<[array count];i++)
		 {
			 AddressTable* targetAddress = [array objectAtIndex:i];
			 NSLog(@"keyword Index - %@",[targetAddress index]);
			 NSLog(@"keyword key - %@",[targetAddress key]);
			 NSLog(@"keyword content - %@",[targetAddress content]);
			 
		 }
		*/
		return [[array retain]autorelease];
	}else {
		NSLog(@"error find id");
		return nil;
	}
}

/*
 * 새로운 기록 정보를 인서트 한다.
 */
-(void)insertNewData
{
	
	track* targetAddress = (track*)[NSEntityDescription insertNewObjectForEntityForName:@"track" inManagedObjectContext:self.managedObjectContext];
	
	
	int indexNumber = [OptionValueManager getIndexNumber];
	[targetAddress setIndex:[NSNumber numberWithInt:indexNumber]];
	[OptionValueManager setIndexNumber:indexNumber++];
	
	NSError* error;
	if(![self.managedObjectContext save:&error])
	{
	//	NSLog(@"error save data %@",error);
	}
	else {
	//	NSLog(@"Success save data");
	}
}


-(track*)getDataInstance
{
	return (track*)[NSEntityDescription insertNewObjectForEntityForName:@"track" inManagedObjectContext:self.managedObjectContext];
}

-(void)saveDataInstance:(track*)targetData
{
	
	int indexNumber = [OptionValueManager getIndexNumber];
	[targetData setIndex:[NSNumber numberWithInt:indexNumber]];
	[OptionValueManager setIndexNumber:indexNumber++];
	
	NSError* error;
	if(![self.managedObjectContext save:&error])
	{
		NSLog(@"error save data %@",error);
	}
	else {
		NSLog(@"Success save data");
	}
}







@end
